const state = {
  cartProducts: []
}
const getters = {
  totalCount ({ cartProducts }) {
    return cartProducts.reduce((a, b) => a + b.count, 0)
  },
  totalPrice ({ cartProducts }) {
    return cartProducts.reduce((a, b) => a + b.count * b.price, 0)
  },
  checkedCount ({ cartProducts }) {
    return cartProducts.reduce((a, b) => a + (b.isChecked ? b.count : 0), 0)
  },
  checkedPrice ({ cartProducts }) {
    return cartProducts.reduce((a, b) => a + (b.isChecked ? b.count * b.price : 0), 0)
  }
}
const mutations = {
  addToCart (state, payload) {
    // 1. 没有该商品，添加至购物车，设置默认数量，是否勾选等属性
    // 2. 如果已有该商品，增加数量
    const product = state.cartProducts.find(item => item.id === payload.id)
    if (product) {
      product.count++
      product.totalCount += product.price
    } else {
      state.cartProducts.push({
        ...payload,
        count: 1,
        isChecked: true,
        totalPrice: payload.price
      })
    }
  },
  deleteFromCart (state, payload) {
    const index = state.cartProducts.findIndex(item => item.id === payload.id)
    index !== -1 && state.cartProducts.splice(index, 1)
  },
  updateAllProductsChecked (state, payload) {
    state.cartProducts.forEach(element => {
      element.isChecked = payload.checked
    })
  },
  updateProductChecked (state, payload) {
    const product = state.cartProducts.find(item => item.id === payload.id)
    product && (product.isChecked = payload.checked)
  },
  updateProduct (state, payload) {
    const product = state.cartProducts.find(item => item.id === payload.id)
    if (product) {
      product.count = payload.count
      product.totalPrice = product.count * product.price
    }
  }
}
const actions = {}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
